<template>
	<div class="login-container">
		<div class="login-box">
			<el-form
				ref="ruleFormRef"
				style="max-width: 600px; width: 100%"
				:model="ruleForm"
				:rules="rules"
				label-width="auto"
				:hide-required-asterisk="true"
				label-position="left"
				@keyup.enter="onSubmit(ruleFormRef)"
			>
				<el-form-item label="用户名" prop="username">
					<el-autocomplete
						:prefix-icon="User"
						v-model="ruleForm.username"
						:fetch-suggestions="querySearch"
						placeholder="请输入用户名"
						clearable
						@change="handleUsernameChange"
						@select="handleUserNameClick"
						@clear="handleClearUsername"
					>
						<template #default="{ item }">
							<div class="value">{{ item.username }}</div>
						</template>
					</el-autocomplete>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input
						:prefix-icon="Lock"
						v-model="ruleForm.password"
						type="password"
						autocomplete="off"
						clearable
						show-password
					/>
				</el-form-item>
				<div class="checkout-box">
					<el-form-item>
						<el-checkbox
							v-model="ruleForm.rememberUsername"
							label="记住用户名"
							size="large"
							@change="handleRememberUsernameChange"
						/>
					</el-form-item>
					<el-form-item>
						<el-checkbox
							v-model="ruleForm.rememberPassword"
							label="记住密码"
							size="large"
							@change="handleRememberPasswordChange"
						/>
					</el-form-item>
				</div>
				<el-form-item style="text-align: center">
					<el-button class="submit" type="primary" @click="onSubmit(ruleFormRef)">登录</el-button>
				</el-form-item>
			</el-form>
			<div class="register-box">
				<el-link type="primary" :underline="false" @click="handleRegisterClick">注册</el-link>
			</div>
		</div>
		<TopTile />
	</div>
</template>
<script lang="ts">
	export default {
		name: 'Login',
	};
</script>
<script setup lang="ts">
	import { nextTick, onMounted, reactive, ref } from 'vue';
	import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
	import { User, Lock } from '@element-plus/icons-vue';
	import type { UserData } from '@/types/commonType';
	import { useRouter } from 'vue-router';
	import { login } from '../api/index';
	console.log('login', login);

	const router = useRouter();
	const { api } = window;

	const userInfoList = ref<UserData[]>([]);
	const querySearch = (queryString: string, callback: any) => {
		const results = queryString ? userInfoList.value.filter(createFilter(queryString)) : userInfoList.value;
		callback(results);
	};
	const createFilter = (queryString: string) => {
		return (userInfo: UserData) => {
			userInfo.username.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
		};
	};

	onMounted(async () => {
		// 初始化时检查是否有存储的凭据
		const allUserData = await api.getAllUserData();
		if (allUserData) {
			userInfoList.value = allUserData;
			ruleForm.username = allUserData[0].username;
			ruleForm.rememberUsername = allUserData[0].rememberUsername;
			if (allUserData[0].rememberPassword) {
				ruleForm.rememberPassword = true;
				ruleForm.password = allUserData[0].password;
			}
		}
	});

	interface RuleForm {
		username: string;
		password: string;
		rememberUsername: boolean;
		rememberPassword: boolean;
	}
	const ruleFormRef = ref<FormInstance>();
	const ruleForm = reactive<RuleForm>({
		username: '',
		password: '',
		rememberUsername: false,
		rememberPassword: false,
	});
	const rules = reactive<FormRules>({
		username: [{ required: true, message: '请输入用户名，长度至少3个字符', trigger: 'blur', min: 3 }],
		password: [{ required: true, message: '请输入密码,长度6到12位', trigger: 'change', min: 6, max: 12 }],
	});
	// 记住用户名
	const handleRememberUsernameChange = (val: boolean) => {
		ruleForm.rememberUsername = val;
	};
	// 记住密码
	const handleRememberPasswordChange = (val: boolean) => {
		ruleForm.rememberPassword = val;
	};
	// 点击清除用户名后
	const handleClearUsername = () => {
		ruleForm.username = '';
		ruleForm.password = '';
		ruleForm.rememberPassword = false;
		ruleForm.rememberUsername = false;
	};
	// 用户名改变时
	const handleUsernameChange = (val: string) => {
		if (val !== '') {
			ruleForm.rememberUsername = true;
		}
	};
	// 选择用户名点击方法
	const handleUserNameClick = (item: UserData) => {
		ruleForm.username = item.username;
		ruleForm.password = item.password;
		ruleForm.rememberUsername = item.rememberUsername;
		ruleForm.rememberPassword = item.rememberPassword;
		nextTick(() => {
			if (ruleFormRef.value) {
				// 清除用户名的验证状态
				ruleFormRef.value.clearValidate(['username']);
			}
		});
	};
	// 登录
	const onSubmit = async (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate((valid, fields) => {
			if (valid) {
				console.log('submit!');
				try {
					login({
						username: ruleForm.username,
						password: ruleForm.password,
						rememberUsername: ruleForm.rememberUsername,
						rememberPassword: ruleForm.rememberPassword,
					}).then(res => {
						console.log('res', res);
						if (res.code === 200) {
							// 使用表单输入的用户名和密码进行登录
							api
								.saveToken({
									username: ruleForm.username,
									password: ruleForm.password,
									rememberUsername: ruleForm.rememberUsername,
									rememberPassword: ruleForm.rememberPassword,
								})
								.then(saveResult => {
									if (saveResult) {
										ElMessage.success('登录成功');
										localStorage.setItem('isLogin', 'true');
										localStorage.setItem('userName', ruleForm.username);
										// 登录成功，跳转到首页
										router.replace({ name: 'home' });
										api.setWindowSize();
									}
								});
						}
					});
				} catch (error) {
					console.error('获取存储的凭据失败:', error);
				}
			} else {
				console.log('error submit!', fields);
			}
		});
	};
	// 注册点击方法
	const handleRegisterClick = () => {
		
		router.push({ name: 'register' });
	};
</script>
<style scoped lang="scss">
	.login-container {
		width: 100%;
		height: 100vh;
		background: linear-gradient(72deg, #ff62a5, #6b76ff);

		.login-box {
			width: 65%;
			padding: 40px 20px;
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			border-radius: 10px;
			background-color: #fff;
			box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
			&:hover {
				box-shadow: 0 0 13px #6b76ff;
			}
			.register-box {
				width: 100%;
				text-align: right;
			}
			.checkout-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
			.submit {
				width: 100%;
			}
		}
	}
</style>
